package guestbook;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.QueryResultList;
//import com.google.appengine.api.datastore.Query.FilterOperator;

@SuppressWarnings("serial")
public class DeleteSensorFiveMins extends HttpServlet{
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	          throws ServletException, IOException {
		String Table = "CompressedData";
		int pageSize = 500;
		FetchOptions fetchOptions = FetchOptions.Builder.withLimit(pageSize);
		String startCursor = req.getParameter("cursor");
		// If this servlet is passed a cursor parameter, let's use it
        if (startCursor != null) {
            fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor));
        }
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		resp.setContentType("text/html");
		PrintWriter o = resp.getWriter();
		Query q = new Query(Table).setKeysOnly();
		
		//q.addFilter("compress", FilterOperator.EQUAL, true);
		
		PreparedQuery pq = datastore.prepare(q);
        
        o.println("Deleting already processed entries in "+Table);
        QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);
        
        List<Key> al = new ArrayList<Key>(); 
        
        for (Entity values : results ) {
        	//o.println(values.getKey()+"  ");
        	al.add(values.getKey());
        }
        
        datastore.delete(al);
        o.println("<br>");

        String cursor = results.getCursor().toWebSafeString();
        if (! results.isEmpty()) {
            o.println("More to delete ..");
            o.println("<script type=\"text/javascript\">");
            o.println("<!--");
            o.println("window.location = \""+ "/del5m?cursor=" + cursor +"\"");
            o.println(" //-->");
            o.println("</script>");
            
           } else o.println("<br><b>FINISHED!</b>");
	}

}
